import { defineStore } from 'pinia'
import type { IDialog, IHandleApi, IStatsChart } from 'vue3-common/types'
import { ElMessage } from 'element-plus'
import { ILedger, ILedgerQuery, ILedgerRecord } from '@/types/ledger'
import { queryAssetCategoryApi } from '@/apis/asset'
import {
  addLedgerApi,
  deleteLedgerApi,
  queryLedgerApi,
  queryLedgerBookApi,
  updateLedgerApi
} from '@/apis/ledger'
import { ImagePathEnum } from '@/types'

export const useLedgerStore = defineStore('ledger', {
  state: () => ({
    ledgerRecordList: [] as ILedgerRecord[],
    ledgerList: [] as ILedger[],
    queryInfo: {
      book: ''
    } as ILedgerQuery,
    ledgerBookList: [] as string[],
    ledgerAmount: 0,
    ledgerApiType: 'ADD' as IHandleApi,
    ledgerImagePath: ImagePathEnum.LEDGER,
    categoryStats: {} as IStatsChart[],
    currentLedgerRecord: {
      id: 0,
      book: '',
      category: '',
      content: '',
      price: 0,
      number: 0,
      unit: '',
      payer: '',
      provider: '',
      imageUrl: '',
      remark: ''
    } as ILedgerRecord,
    ledgerDialog: {
      visible: false,
      title: '',
      data: {}
    } as IDialog<ILedgerRecord>,
    isRefresh: false
  }),
  actions: {
    async queryLedgerList() {
      this.ledgerRecordList = await queryLedgerApi(this.queryInfo.book)

      this.ledgerList = []
      this.parseLedgerList()
    },
    parseLedgerList() {
      const groupedData = this.ledgerRecordList.reduce((acc, item) => {
        const { category } = item
        if (!acc[category]) {
          acc[category] = []
        }
        acc[category].push(item)
        return acc
      }, {})

      this.ledgerList = Object.entries(groupedData).map(([category, group]) => {
        const totalAmount = group.reduce((sum, { totalPrice }) => sum + totalPrice, 0)
        const itemList = group.map(({ id, content, price, number, unit, totalPrice,
          payer, provider, imageUrl, remark }) => ({
          id,
          content,
          price,
          number,
          unit,
          totalPrice,
          payer,
          provider,
          imageUrl,
          remark
        }))
        return {
          category,
          totalAmount,
          itemList
        }
      })

      this.ledgerAmount = this.ledgerList.reduce((sum, current) => sum + current.totalAmount, 0)
    },
    async queryLedgerBook() {
      this.ledgerBookList = await queryLedgerBookApi()
    },
    async handleLedgerApi(ledger: ILedgerRecord) {
      switch (this.ledgerApiType) {
        case 'ADD':
          await addLedgerApi(ledger)
          ElMessage.success('新增账本内容成功')
          break
        case 'UPDATE':
          await updateLedgerApi(ledger.id as number, ledger)
          ElMessage.success('更新账本内容成功')
          break
        case 'DELETE':
          await deleteLedgerApi(ledger.id as number)
          ElMessage.success('删除账本内容成功')
          break
        default:
          break
      }
      this.ledgerDialog.visible = false
      await this.refreshInfo()
    },
    async refreshInfo() {
      await this.queryLedgerList()
      this.isRefresh = !this.isRefresh
    },
    getEmptyLedgerRecord(): ILedgerRecord {
      return {
        book: '',
        category: '',
        content: '',
        id: 0,
        imageUrl: '',
        number: 0,
        payer: '',
        price: 0,
        provider: '',
        remark: '',
        unit: ''
      }
    }
  }
})
